#include "Framework/Win32/Win32FileService.h"

#include "Core/Kernel.h"
#include "Core/LogService.h"

#include <cassert>
#include <cstdio>

namespace Orca {

	//--------------------------------------------------------------------------
	ORCA_IMPLEMENT_SERVICE(FileService)

	//--------------------------------------------------------------------------
	Win32FileService::Win32FileService() {

	}

	//--------------------------------------------------------------------------
	Win32FileService::~Win32FileService() {

	}

	//--------------------------------------------------------------------------
	bool Win32FileService::startup() {

		return true;
	}

	//--------------------------------------------------------------------------
	void Win32FileService::step(float dt) {

	}

	//--------------------------------------------------------------------------
	void Win32FileService::shutdown() {

	}

	//--------------------------------------------------------------------------
	bool Win32FileService::readFile(
		  const Str &filename
		, uint8 *&outDataBuffer
		, uint32 &outDataLength) {

		FILE *fp = fopen(filename.c_str(), "rb");

		if(!fp)
		{
			LOG_ERR(
				"Win32FileService: Failed to read file - " + filename +
				"\n\tFopen failed");

			return false;
		}

		fseek(fp, 0, SEEK_END);
		outDataLength = (uint32)ftell(fp);
		outDataBuffer = new uint8[outDataLength + 1];

		fseek(fp, 0, SEEK_SET);
		fread(outDataBuffer, outDataLength, 1, fp);

		outDataBuffer[outDataLength] = '\0';

		fclose(fp);

		return true;
	}

	//--------------------------------------------------------------------------
	bool Win32FileService::writeFile(
		 const Str &filename
		, uint8 *inDataBuffer
		, uint32 inDataLength) {

		FILE *fp = fopen(filename.c_str(), "wb");

		if(!fp)
		{
			LOG_ERR(
				"Win32FileService: Failed to write file - " + filename +
				"\n\tFopen failed");

			return false;
		}

		fwrite(inDataBuffer, inDataLength, 1, fp);

		fclose(fp);

		return true;
	}

	//--------------------------------------------------------------------------
}